package com.wushijia.highconcurrency.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * description: ThreadFactory:创建线程
 *
 * @author yang
 * @date 2018/5/22 20:11
 */
@Slf4j
public class ThreadPoolExecutorTest1 {

  public static void main(String[] args) throws InterruptedException {
    MyTask task = new MyTask();
    ExecutorService executorService = new ThreadPoolExecutor(1, 2, 0L, TimeUnit.MILLISECONDS,
        new ArrayBlockingQueue<>(1), new ThreadFactory() {
      @Override
      public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(true);
        //线程异常退出时，执行到runWorker->processWorkerExit，会补充新的线程执行queue里面的任务
        log.info("create " + t);
        return t;
      }
    });
    for (int i = 0; i < 10; i++) {
      try {
        //如果超出线程池处理能力，则会抛出拒绝执行异常（JVM触发dispatchUncaughtException方法），需手动处理
        executorService.execute(task);
      } catch (RejectedExecutionException e) {
        //线程池拒绝执行异常处理
        log.error("线程池已满，拒绝新连接");
      }

    }
    Thread.sleep(2000);
//    executorService.shutdown();
  }

  public static class MyTask implements Runnable {

    @Override
    public void run() {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("myTask is running...");
    }
  }
}
